﻿using System; using HISModels.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KeanuMvc.Reference;
using HIS.Utils;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using HISModels.Entities;
using System.Configuration;


namespace HIS.Controllers.Admins {

    public class Membership : HIS.Controllers.AppBaseController {

        #region Fields
        private string strAction = string.Empty;
        private string strNotification = string.Empty;
        private HISModels.Entities.SysMembership sysMembership = null;
        private HISModels.Entities.MemberEmployee memEmployee = null;
        #endregion

        #region Constructors
        public Membership() {
            Data.Add("Pagetitle", "Memberships");
            Data.Add("Notification", strNotification);
        }

        #endregion

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public override void Index() {
            try {
                Data.Add("DdLocation", GetLocation("DdLocation", base.RestService, null).NullSafeToString());
                RenderFile("admins\\memberships\\membership.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public void TableList() {
            ///Set variables///
            StringReader stringReader = null;
            string strJson = string.Empty;

            try {
                string TextboxMemberUserId = HttpContext.Current.Request["TextboxMemberUserId"].NullSafeToString();
                string DdLocation = HttpContext.Current.Request["DdLocation"].NullSafeToString();
                string TextBoxRole = HttpContext.Current.Request["TextBoxRole"].NullSafeToString();
                string ssearch = "TextboxMemberUserId=" + TextboxMemberUserId + ";DdLocation=" + DdLocation + ";TextBoxRole=" + TextBoxRole;
                ///--------- Sample post to rest and get record as paging-------------/// 
                ///Create paging object///
                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);
                if (!string.IsNullOrEmpty(ssearch)) {
                    pagingSearch.sSearch = ssearch;
                } else { pagingSearch.sSearch = Convert.ToString(HttpContext.Current.Request["sSearch"]); }
                
                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);

                ///Set Rest Url///
                //string strUri = Data["servicerooturl"] + "sys/membership/paging/?format=json";

                string strUri = Global.ServiceUriDictionary["membershippaging"] + Global.ServiceUriDictionary["requestformat"];
                ///Post paging object to rest as json string///
                stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Read response value///
                strJson = stringReader.ReadToEnd();
                ///----------Consistenly clean up all object------------///
                
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            } finally {
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public void EditMembership() {
            HISModels.Entities.SysMembership sysMembership = new SysMembership();
            ///Set variables///
            StringReader stringReader = null;
            /// Get id record from querystring
            int id = 0;
            int empId = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("membership/");
                return;
            }

            try {
                ///Set Rest Url///
                //string strUri = Data["servicerooturl"] + "sys/membership/" + id + "?format=json";
                string strUri = Global.ServiceUriDictionary["membership"] + id + Global.ServiceUriDictionary["requestformat"];
                ///Get Rest///
                stringReader = base.RestService.GetJson(strUri);
                JObject JObj1 = JObject.Parse(stringReader.ReadToEnd());
                sysMembership.UserId = (string)JObj1["Detail"][0]["UserId"];
                string empName = (string)JObj1["Detail"][0]["name"];
                string aa = Convert.ToString(JObj1["Detail"][0]["employeeid"]);
                if (aa != "") {
                    empId = (Int32)JObj1["Detail"][0]["employeeid"];
                } 
                else
                sysMembership.Id = (Int32)JObj1["Detail"][0]["membershipid"];
                sysMembership.RoleId = (Int32)JObj1["Detail"][0]["RoleId"];
                sysMembership.IsApproved = (Int32)JObj1["Detail"][0]["IsApproved"];
                ///Deserialize json response to object///
                //sysMembership = JsonConvert.DeserializeObject<SysMembership>(stringReader.ReadToEnd());
                ///Set variable for rendering on view HTML///
                //if (sysMembership. == null) {
                //    sysRole.DefaultUrl = "";
                //}
                
                Data.Add("sysMembership", sysMembership);
                Data.Add("IsCreate", "false");
                /// Another var to render
                Data.Add("ddlSetDDL", SetDDL("ddlSetDDL", null));
                Data.Add("ddroles", DropDownRole(sysMembership.RoleId.NullSafeToString()));
                Data.Add("empName", empName.NullSafeToString());
                Data.Add("empId", empId);
                strUri = Global.ServiceUriDictionary["hospitalrole"] + sysMembership.RoleId + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.GetJson(strUri);
                RefHu oHospital = JsonConvert.DeserializeObject<RefHu>(stringReader.ReadToEnd());

                Data.Add("Location", oHospital.NameValue.NullSafeToString());
                Data.Add("IdLocation", oHospital.Id.NullSafeToString());
                Data.Add("ddstatus", Utils.Helper.DropDownOptions(base.RestService, sysMembership.IsApproved.NullSafeToString(), 1));
                Data.Add("Actionform", Data["rooturl"] + "admins/membership/editmembership/?id=" + id);
                Data["Pagetitle"] += " :: Edit member";
                Data["Notification"] = strNotification;
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                RenderFile("Admins\\Memberships\\editmembership.html");
                if (stringReader != null) stringReader.Dispose();
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public void DeleteMembership() {
            ///Set variables///
            StringReader stringReader = null;
            int id = 0;
            try {
                id = Convert.ToInt32(HttpContext.Current.Request["id"]);
            } catch {
                GoToUrl("membership/");
                return;
            }

            try {
                //string strUri = Data["servicerooturl"] + "sys/membership/?format=json";
                string strUri = Global.ServiceUriDictionary["membership"] + Global.ServiceUriDictionary["requestformat"];
                stringReader = base.RestService.DeleteJson(strUri, JsonConvert.SerializeObject(id));
                sysMembership = JsonConvert.DeserializeObject<SysMembership>(stringReader.ReadToEnd());
                strNotification = Helper.SuccessMessage("Data Has Been Successfully Deleted");
            } catch (Exception ex) {
                Data["Notification"] = Helper.ErrorMessage(ex.Message);
            } finally {
                HttpContext.Current.Response.Write(strNotification);
                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public void SaveMembershipsToService()
        {
            HISModels.Entities.MemberEmployee memEmployee = new MemberEmployee();
            StringReader stringReader = null;
            string strUri = string.Empty;
            int id = 0;
            int idEmp = 0;
            try
            {
                sysMembership = new SysMembership(); Utils.Helper.SetNullToEmptyString(sysMembership);
                if (HttpContext.Current.Request["IsCreate"] != "true")
                {

                    try
                    {
                        id = Convert.ToInt32(HttpContext.Current.Request["id"]);
                        idEmp = Convert.ToInt32(HttpContext.Current.Request["IdEmployee"]);
                    }
                    catch { }
                    strUri = Global.ServiceUriDictionary["membership"] + id + Global.ServiceUriDictionary["requestformat"];
                    ///Get Rest///
                    stringReader = base.RestService.GetJson(strUri);
                    sysMembership = JsonConvert.DeserializeObject<SysMembership>(stringReader.ReadToEnd());
                }

                sysMembership.PostHandler<HISModels.Entities.SysMembership>();
                sysMembership.UserId = HttpContext.Current.Request["UserId"];
                sysMembership.IsApproved = Convert.ToInt32(HttpContext.Current.Request["StatusId"]);
                memEmployee.MembershipId = id;
                memEmployee.EmployeeId = idEmp;
                strUri = Global.ServiceUriDictionary["membership"] + Global.ServiceUriDictionary["requestformat"];

                if (HttpContext.Current.Request["IsCreate"] == "true")
                {
                    stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(sysMembership));
                }
                else
                {
                    stringReader = base.RestService.PutJson(strUri, JsonConvert.SerializeObject(sysMembership));
                    if (idEmp != 0) {
                        strUri = Global.ServiceUriDictionary["memberemployees"] + Global.ServiceUriDictionary["requestformat"];
                        stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(memEmployee));
                        memEmployee = JsonConvert.DeserializeObject<MemberEmployee>(stringReader.ReadToEnd());
                    }
                    
                    
                }


                sysMembership = JsonConvert.DeserializeObject<SysMembership>(stringReader.ReadToEnd());

                if (sysMembership != null || memEmployee != null)
                {
                    strNotification = Helper.SuccessMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }
                else
                {
                    strNotification = Helper.ErrorMessage(base.RestService.ObjectResponse.Headers[HISModels.Enums.ResponseMessage.DetailHeadesMessageKey].ToString());
                }


                strNotification = "{\"strNotification\": \"" + strNotification + "\"}";
                HttpContext.Current.Response.Write(strNotification);

            }
            catch (Exception ex)
            {
                strNotification = ex.Message;
            }
            finally
            {

                base.RestService.Dispose();
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public string DropDownRole(string Selected) {
            StringReader stringReaderDropDown = null;
            string strResult = string.Empty;
            string strUri = Global.ServiceUriDictionary["role"] + Global.ServiceUriDictionary["requestformat"];
            try {
                stringReaderDropDown = base.RestService.GetJson(strUri);
                List<SysRole> listRole = JsonConvert.DeserializeObject<List<SysRole>>(stringReaderDropDown.ReadToEnd());
                List<object[]> activeArr = new List<object[]>();
                foreach (SysRole item in listRole) activeArr.Add(new object[] { item.RoleId, item.DescValue });
                strResult = KeanuMvc.Reference.Html.DropDown("RoleId", string.Empty, activeArr, Selected);
                activeArr.Clear();
                activeArr = null;
            } catch {
            } finally {
                stringReaderDropDown.Dispose();
            }
            return strResult;
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public string GetLocation(string name,KeanuMvc.Reference.ClientRestService clientService, string Selected) {
            string strResult = string.Empty;

            string strUri = Global.ServiceUriDictionary["hospital"] + Global.ServiceUriDictionary["requestformat"];
            StringReader stringReader = clientService.GetJson(strUri);
            List<RefHu> listOption = JsonConvert.DeserializeObject<List<RefHu>>(stringReader.ReadToEnd());

            List<object[]> listDropdown = new List<object[]>();
            listDropdown.Add(new object[] { "-1", "--Select--" });
            foreach (RefHu item in listOption) {
                listDropdown.Add(new object[] { item.Id, item.NameValue });
            }

            strResult = KeanuMvc.Reference.Html.DropDown(name, string.Empty, listDropdown, Selected);
            listDropdown.Clear();
            listDropdown = null;
            stringReader.Dispose();
            return strResult;
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public string SetDDL(string id, string Selected) {
            string strResult = string.Empty;
            List<object[]> listDropdown = new List<object[]>();
            listDropdown.Add(new object[] { "0", "--Select--" });
            listDropdown.Add(new object[] { "1", "Doctor" });
            listDropdown.Add(new object[] { "2", "Employee" });
            strResult = KeanuMvc.Reference.Html.DropDown(id, string.Empty, listDropdown, Selected);
            listDropdown.Clear();
            listDropdown = null;
            
            return strResult;
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public void SearchEmployee() {
            try {
                //Data.Add("ddlocation", DropDownHospital(string.Empty));
                string id = HttpContext.Current.Request["idlocation"];
                Data.Add("HusId", id);
                RenderFile("admins\\memberships\\seachemployee.html");
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }

        [HIS.Utils.Securities.Authorization(RoleAction = "sys-membership")]
        public void SearchEmployeeTableList() {
            try {
                ///--------- Sample post to rest and get record as paging-------------/// 
                ///Create paging object///
                PostDataTablesNet pagingSearch = new PostDataTablesNet();
                pagingSearch.iDisplayLength = Convert.ToInt32(HttpContext.Current.Request["iDisplayLength"]);
                pagingSearch.iDisplayStart = Convert.ToInt32(HttpContext.Current.Request["iDisplayStart"]);

                int id = Convert.ToInt32(HttpContext.Current.Request["idlocation"]);
                string employeenumber = HttpContext.Current.Request["employeenumber"].NullSafeToString();
                string name = HttpContext.Current.Request["name"].NullSafeToString();
                //int hospitalid = Convert.ToInt32(HttpContext.Current.Request["hospitalid"]);

                pagingSearch.sSearch = "employeenumber=" + employeenumber + ";name=" + name + ";id=" + id;

                pagingSearch.sEcho = Convert.ToInt32(HttpContext.Current.Request["sEcho"]);
                //
                ///Set Rest Url///
                string strUri = Global.ServiceUriDictionary["employeepaging"] + Global.ServiceUriDictionary["requestformat"];
                ///Post paging object to rest as json string///
                StringReader stringReader = base.RestService.PostJson(strUri, JsonConvert.SerializeObject(pagingSearch));
                ///Read response value///
                string strJson = stringReader.ReadToEnd();
                ///----------Consistenly clean up all object------------///
                stringReader.Dispose();
                base.RestService.Dispose();
                HttpContext.Current.Response.Write(strJson);
            } catch (Exception ex) {
                HttpContext.Current.Response.Write(ex.Message);
            }
        }
    }
}

